<template>
    <div class="deployPlatform-container">
        <MCard>
          <template #header>
            <span>查询部署文件信息</span>
          </template>
           <div class="header flex justify-between">
             <el-form :inline="true">
              <el-form-item label="部署文件名称" prop="deploymentName">
                <el-input style="width: 200px;" v-model="deployPlatformForm.deploymentName"  placeholder="输入部署平台名称"/>
              </el-form-item>
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker popper-class="starMange_Picker" style="width: 230px;" v-model="deployPlatformForm.startTime" placeholder="选择开始时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker popper-class="starMange_Picker" style="width: 220px;" v-model="deployPlatformForm.endTime" placeholder="选择结束时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
              </el-form-item>
              <el-form-item>
                <div class="global_btn" style="width: 100px;" v-globalBtnLoading="handleSearch">查询</div>
              </el-form-item>
             </el-form>
            <div class="global_btn" style="width: 100px;" v-globalBtnLoading="handleAdd">新增部署</div>
           </div>
        </MCard>
        <MCard>
          <template #header>
            <span>部署文件列表</span>
          </template>
           <el-table 
           :data="deployPlatformList" 
           max-height="400px"
           :key="tableKey"
           >
            <el-table-column label="编号" type="index" width="80px" />
            <el-table-column label="部署文件ID" prop="deploymentId" />
            <el-table-column label="部署文件名称" prop="deploymentName" />
            <el-table-column label="版本号" prop="versionNumber" />  
            <el-table-column label="提交ID" prop="commitId" />  
            <el-table-column label="提交信息" prop="commitMessage" />  
            <el-table-column label="构建时间" prop="createdTime" />  
            <el-table-column label="操作"  >  
              <template #default="scope">
                <div class="flex gap-10px">
                  <div style="width: 80px;" class="global_btn" @click="handleDetail(scope.row)">详情</div>
                  <div style="width: 80px;" class="global_btn" v-globalBtnLoading="{
                    handler:()=>handleDelete(scope.row),
                    text:'删除中...'
                  }">删除</div>
                </div>
              </template>
            </el-table-column>
           </el-table>
           <div class="flex justify-end m-t-20px">
            <el-pagination
            v-model:currentPage="pageData.currentPage"
            v-model:page-size="pageData.pageSize"
            :page-sizes="[3,5,7,10]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageTotal"
            @size-change="handleGetDeployPlatformList"
            @current-change="handleGetDeployPlatformList"
            size="small"
           />
           </div>         
         </MCard>
        <MDialog
          v-bind="addDeployDialogData"
          v-model:dialogVisible="addDeployDialogData.visible"
        >
          <template #content>
            <el-form 
            :model="uploadForm" 
            ref="uploadFormRef" 
            :rules="uploadFormRules" 
            labelPosition="left"
            labelWidth="100px"
            >
              <el-form-item label="版本号" prop="version">
                <el-input v-model="uploadForm.version" />
              </el-form-item>
              <el-form-item label="提交信息" prop="commitMessage">
                <el-input v-model="uploadForm.commitMessage" type="textarea" :rows="3" />
              </el-form-item>
              <el-form-item label="运行命令" prop="runCommand">
                <el-input v-model="uploadForm.runCommand" type="textarea" autosize />
              </el-form-item>
              <el-form-item label="文件" prop="file">
                <UploadFile v-model:file="uploadForm.file" />
              </el-form-item>
              <el-form-item>
                <div class="flex justify-end w-full gap-20px">
                  <div class="global_btn" style="width: 200px;" v-globalBtnLoading="{
                    handler:handleUpload,
                    text:'新增中...'
                  }">新增</div>
                </div>
              </el-form-item>
            </el-form>
          </template>
        </MDialog>
        <Mprogress 
      :show="uploadForm.showProgress"
      :progress="uploadForm.progress"
      title="上传文件"
      progressText="正在上传文件"
      waitingText="耐心等待，上传完成后将自动保存..."
      completeText="上传完成，即将保存文件..."
      primaryColor="#00d1ed"
      @close="cancelUpload"
         />
    </div>
  </template>
  <script lang="ts">
  import { defineComponent } from 'vue'
  export default defineComponent({
    name: 'DeployPlatform',
  })
  </script>
  
  <script setup  lang="ts">
  import UploadFile from "@/components/UploadFile.vue"
  import { deployPlatformApi } from "@/api/deployPlatform"
  import axios from "axios"
  import { ElMessage } from "element-plus"
  import { ElNotificationFn } from "@/utils/computedUtils"
  import { useRouter } from "vue-router"
  import dayjs from "dayjs"
  const router = useRouter()
  const tableKey = ref(0)
  const deployPlatformForm = ref<any>({
    deploymentName:"",
    startTime:"",
    endTime:"",
  })
  async function handleSearch(){
    console.log(deployPlatformForm.value,"1111");
    if(!deployPlatformForm.value.deploymentName && !deployPlatformForm.value.startTime && !deployPlatformForm.value.endTime){
      ElNotificationFn("warning","至少选择一个查询条件")
      return
    }
    await handleGetDeployPlatformList()
  }
  async function handleAdd(){
    addDeployDialogData.value.visible = true
  }
  const addDeployDialogData = ref<any>({
    title:"新增部署",
    width:"600px",
    visible:false,
  })
  const uploadForm = ref<any>({
    version:"",
    file:"",
    commitMessage:"",
    runCommand:"",
    progress:0,
    showProgress:false,
  })
  const uploadFormRef = ref<any>()
  const uploadFormRules = ref<any>({
    version:[{required:true,message:"输入版本号",trigger:"blur"}],
    file:[{required:true,message:"上传文件",trigger:"blur"}],
    commitMessage:[{required:true,message:"输入提交信息",trigger:"blur"}],
    runCommand:[{required:true,message:"输入运行命令",trigger:"blur"}],
  })
  let cancelToken:any = null
  async function handleUpload(){
    try {
      await uploadFormRef.value.validate()
      const formData = new FormData()
      formData.append("versionNumber", uploadForm.value.version)
      formData.append('deploymentName',uploadForm.value.file.name)
      formData.append('commitMessage',uploadForm.value.commitMessage)
      formData.append('startupScript',uploadForm.value.runCommand)
      if (!uploadForm.value.file || !(uploadForm.value.file instanceof File)) {
        ElMessage.error('请选择有效的文件')
        return
      }
      formData.append("file", uploadForm.value.file)
      cancelToken = axios.CancelToken.source() 
      try {
        uploadForm.value.showProgress = true
        await deployPlatformApi.uploadFile(
          formData, 
          uploadProgressFn, 
          cancelToken.token 
        )
        addDeployDialogData.value.visible = false
        uploadForm.value.progress = 0
        uploadForm.value.showProgress = false
        ElNotificationFn("success","上传成功")
         handleGetDeployPlatformList()
      } catch (uploadError: any) {
       
      }
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
function uploadProgressFn(progressEvent:any){
   const newProgress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
   const updateProgress = () => {
    const currentProgress = uploadForm.value.progress;
    if (currentProgress < newProgress) {
              uploadForm.value.progress = Math.min(currentProgress + 1, newProgress);
              if (uploadForm.value.progress < newProgress) {
                requestAnimationFrame(updateProgress);
              }
            }
          };
      updateProgress();
}
function cancelUpload(){
  cancelToken.cancel()
  uploadForm.value.showProgress = false
  uploadForm.value.progress = 0
  cancelToken = null
  ElNotificationFn("warning","上传已取消")
}
const pageData = ref<any>({
  pageSize:10,
  currentPage:1,
})
const pageTotal = ref<number>(0)
const deployPlatformList = ref<any[]>([])
async function handleGetDeployPlatformList(){
  const {data} = await deployPlatformApi.getDeployPlatformList({
    ...pageData.value,
    ...deployPlatformForm.value
  })
  deployPlatformList.value = data.records.map((item:any)=>{
    return {
      ...item,
      createdTime:dayjs(item.createdTime).format("YYYY-MM-DD HH:mm:ss")
    }
  })
  pageTotal.value = data.total
}
function handleDetail(row:any){
  router.push({
    path:"/deployPlatform/deploymentManagement",
    query:{
      deploymentId:row.deploymentId
    }
  })
}
async function handleDelete(row:any){
  try {
    await deployPlatformApi.batchDeleteDeployPlatform(
      [row.deploymentId]
    )
    ElNotificationFn("success","删除成功")
    await handleGetDeployPlatformList()
    tableKey.value++;
  } catch (error) {
    
  }
}
onMounted(()=>{
  handleGetDeployPlatformList()
})

</script>
<style  lang="scss" scoped>
@import "@/styles/input.scss";
@import "@/styles/card.scss";
@import "@/styles/form.scss";
@import "@/styles/data_picker.scss";
@import '@/styles/table.scss';
@import '@/styles/pagination.scss';

.deployPlatform-container{
    width: 100%;
    height: 100%;
  }
</style>